import { createRef, RefObject } from 'react'
import type { Result } from 'ahooks/lib/useRequest/src/types'
import { create } from 'zustand'
import { AgGridReact } from '@ag-grid-community/react'

import { apiDelAttachment, apiEditAttachmentType } from './apis'
import { IAttachmentListItem } from './interface'

export type TRequest = Result<IAttachmentListItem[], []>

export interface IStore {
  gridRef: RefObject<AgGridReact<IAttachmentListItem>>
  request?: TRequest
  getData: (scrollToTop?: boolean) => void
  changeFileType: (fileId: number, fileType: number) => Promise<void>
  delAttachment: (fileId: number) => Promise<void>
}

export const useBoundStore = create<IStore>((_set, get) => {
  return {
    gridRef: createRef(),
    getData: scrollToTop => {
      const { gridRef, request } = get()
      request?.run()
      if (scrollToTop) gridRef.current?.api?.ensureIndexVisible(0, 'top')
    },
    changeFileType: async (fileId, fileType) => {
      await apiEditAttachmentType(fileId, fileType)
      const mutate = get().request?.mutate
      mutate?.(oldData => {
        if (!oldData) return
        return oldData.map(d => {
          if (d.fileId === fileId) return { ...d, fileType }
          return d
        })
      })
    },
    delAttachment: async fileId => {
      await apiDelAttachment(fileId)
      const mutate = get().request?.mutate
      mutate?.(oldData => {
        if (!oldData) return
        return oldData.map(d => {
          if (d.fileId === fileId) return { ...d, deleteFlag: 1 }
          return d
        })
      })
    },
  }
})
